﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.InfoCollect;
using ZBJF.Warranty.Common.Enums.SocketEnum;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.Product;
using ZBJF.Warranty.Model.ViewModel.SocketModel;
using ZBJF.Warranty.Model.ViewModel.SortingCenter;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.CustomerService.Controllers
{
    public class WorkOrderCommonInfoController : BaseController
    {
        /// <summary>
        /// 保单信息
        /// </summary>
        /// <returns></returns>
        public ActionResult InsuranceOrderInfo(int insuranceWarrantyRecordID)
        {
            var insuranceWarrantyRecord =
                 ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(insuranceWarrantyRecordID);
            return View(insuranceWarrantyRecord);
        }
        /// <summary>
        /// 合同凭证
        /// </summary>
        /// <returns></returns>
        public ActionResult InsuranceWarrantyRecordContractInfo(int insuranceWarrantyRecordID)
        {
            var insuranceWarrantyRecord =
               ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(insuranceWarrantyRecordID);
            return View(insuranceWarrantyRecord);
        }
        /// <summary>
        /// 销售商信息
        /// </summary>
        /// <returns></returns>
        public ActionResult InsuranceOrderSellerInfo(int insuranceWarrantyRecordID)
        {
            var insuranceWarrantyRecord =
               ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(insuranceWarrantyRecordID);
            return View(insuranceWarrantyRecord);
        }
        /// <summary>
        /// 保单服务信息
        /// </summary>
        /// <returns></returns>
        public ActionResult InsuranceOrderServiceHistory(int insuranceWarrantyRecordID)
        {
            var insuranceWarrantyRecord =
                ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(insuranceWarrantyRecordID);
            return View(insuranceWarrantyRecord);
        }
        /// <summary>
        /// 工单信息
        /// </summary>
        /// <returns></returns>
        public ActionResult WorkOrderInfo(int insuranceWarrantyRecordID)
        {
            var insuranceWarrantyRecord =
                ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(insuranceWarrantyRecordID);
            return View(insuranceWarrantyRecord);
        }
        /// <summary>
        /// 报案信息
        /// </summary>
        /// <param name="insuranceWarrantyRecordID"></param>
        /// <returns></returns>
        public ActionResult ReportInfo(int insuranceWarrantyRecordID)
        {
            var insuranceWarrantyRecord =
                           ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(insuranceWarrantyRecordID);
            return View(insuranceWarrantyRecord);
        }

        /// <summary>
        /// 快递信息
        /// </summary>
        /// <returns></returns>
        public ActionResult InsuranceWarrantyRecordExpressInfo(int insuranceWarrantyRecordId)
        {
            var insuranceWarrantyRecord = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(insuranceWarrantyRecordId);
            return View(insuranceWarrantyRecord);
        }
        #region 通融相关
        /// <summary>
        /// 通融历史
        /// </summary>
        /// <param name="insuranceWarrantyRecordId"></param>
        /// <returns></returns>
        public ActionResult InsuranceWarrantyBendTheRulesRecordInfo(int insuranceWarrantyRecordId)
        {
            var insuranceWarrantyRecord =
                ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(
                    insuranceWarrantyRecordId);
            return View(insuranceWarrantyRecord);
        }
        #region 保存维修通融记录
        public ActionResult SaveInsuranceWarrantyBendTheRulesRecord(InsuranceWarrantyBendTheRulesRecord model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Add
            };
            var iwrImages = Request.Files;
            string folderName = string.Format("/UploadFile/File/workOrder/{0:yyyy/MM/dd}/{1}/", DateTime.Now, EnumHelper.Instance.GetDescription(typeof(BendTheRulesWithType), model.BendTheRulesWith));
            string fullPath = Server.MapPath(folderName);
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    model.CreatedBy = CurrentUser.UserAccount;
                    model.CreatedTime = DateTime.Now;
                    responseResult.Success = ServiceFactory.InsuranceWarrantyBendTheRulesRecordServiceInstance.AddEntities(model).ID > 0;
                    if (responseResult.Success)
                    {
                        if (iwrImages != null && iwrImages.Count > 0)
                        {
                            for (int i = 0; i < iwrImages.Count; i++)
                            {
                                var uploadFile = new UploadFiles();
                                var iwrImage = iwrImages[i];
                                if (iwrImage == null)
                                {
                                    responseResult.Message = "选择的图片格式有误或者没有选择上传的图片！";
                                    continue;
                                }
                                string fileName = System.Guid.NewGuid().ToString() + ".png";
                                bool result = FileHelper.GetPicThumbnail(iwrImage, 0, fullPath, fileName);
                                if (!result)
                                {
                                    responseResult.Message = "图片保存错误！";
                                    continue;
                                }
                                uploadFile.FileBelongTableName = NeedUploadFileDataTableEnums
                                    .InsuranceWarrantyBendTheRulesRecord.ToString();
                                uploadFile.FileBelongTablePKID = model.ID;
                                uploadFile.FilePath = folderName + fileName;
                                uploadFile.FileName = fileName;
                                uploadFile.FileSize = iwrImage.ContentLength;
                                uploadFile.CreateBy = CurrentUser.UserAccount;
                                uploadFile.CreateTime = DateTime.Now;
                                responseResult.Success = ServiceFactory.UploadFilesServiceInstance.AddEntities(uploadFile).ID > 0;
                            }
                        }
                    }

                    if (responseResult.Success)
                    {
                        ts.Complete();
                    }
                    else
                    {
                        ts.Dispose();
                    }
                }
                catch (Exception e)
                {
                    responseResult.Message = e.ToString();
                    ts.Dispose();
                }
            }
            var insuranceWarrantyRecord = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(model.InsuranceWarrantyRecordID);
            ViewBag.BendTheRulesWith = model.BendTheRulesWith;
            return PartialView("InsuranceWarrantyBendTheRulesRecordInfo", insuranceWarrantyRecord);
        }
        #endregion

        #region 删除通融图片
        [HttpPost]
        public ActionResult DeleteInsuranceWarrantyBendTheRulesRecord(int id)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Delete
            };
            var entity = ServiceFactory.InsuranceWarrantyBendTheRulesRecordServiceInstance.LoadById(id);
            if (entity == null)
            {
                responseResult.Message = "通融记录已不存在！";
            }
            else
            {
                responseResult.Success = ServiceFactory.InsuranceWarrantyBendTheRulesRecordServiceInstance.DeleteEntities(entity);
            }
            return Json(new
            {
                success = responseResult.Success,
                message = responseResult.Message
            });
        }
        #endregion
        #endregion


        #region 信息收集
        /// <summary>
        /// 
        /// </summary>
        /// <param name="insuranceWarrantyRecordId"></param>
        /// <param name="type">ShowResult只显示结果，否则可以上传图片</param>
        /// <param name="collectWithType"></param>
        /// <returns></returns>
        public ActionResult InfoCollectItems(int insuranceWarrantyRecordId)
        {
            var insuranceWarrantyRecord = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(insuranceWarrantyRecordId);
            return View(insuranceWarrantyRecord);
        }

        /// <summary>
        /// 信息收集
        /// </summary>
        /// <param name="model"></param>
        /// <param name="insuranceWarrantyRecordInfoCollect"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveInfoCollect(InsuranceWarrantyRecordInfoCollect model, List<string> insuranceWarrantyRecordInfoCollect)
        {
            var responseResult = new ResponseResult();
            var entity = ServiceFactory.InsuranceWarrantyRecordInfoCollectServiceInstance.Load(model.InsuranceWarrantyRecordID, model.InfoCollectWith, model.InfoColectItemID);
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    if (entity == null)
                    {
                        model.CreateBy = CurrentUser.UserAccount;
                        model.CreateTime = DateTime.Now;
                        model.HadUploadPicCount = (insuranceWarrantyRecordInfoCollect != null && insuranceWarrantyRecordInfoCollect.Any() ? insuranceWarrantyRecordInfoCollect.Count : 0);
                        responseResult.OpreateType = OpreateType.Add;
                        entity = ServiceFactory.InsuranceWarrantyRecordInfoCollectServiceInstance.AddEntities(model);
                        responseResult.Success = entity.ID > 0;
                    }
                    else
                    {
                        entity.HadUploadPicCount = ServiceFactory.UploadFilesServiceInstance
                            .GetFiles(NeedUploadFileDataTableEnums.InsuranceWarrantyRecordInfoCollect, entity.ID)
                            .Count() + (insuranceWarrantyRecordInfoCollect != null && insuranceWarrantyRecordInfoCollect.Any() ? insuranceWarrantyRecordInfoCollect.Count : 0);
                        responseResult.OpreateType = OpreateType.Update;
                        responseResult.Success =
                            ServiceFactory.InsuranceWarrantyRecordInfoCollectServiceInstance.UpdateEntities(entity);
                    }
                    if (responseResult.Success)
                    {
                        if (insuranceWarrantyRecordInfoCollect != null && insuranceWarrantyRecordInfoCollect.Any())
                        {
                            var result = true;
                            for (int i = 0; i < insuranceWarrantyRecordInfoCollect.Count; i++)
                            {
                                if (!result)
                                    break;
                                var uploadFile = new UploadFiles
                                {
                                    FileBelongTableName = NeedUploadFileDataTableEnums
                                        .InsuranceWarrantyRecordInfoCollect.ToString(),
                                    FileBelongTablePKID = entity.ID,
                                    CreateBy = CurrentUser.UserAccount,
                                    CreateTime = DateTime.Now
                                };
                                string aLength = "";
                                string absulotePath;
                                uploadFile.FilePath = FileHelper.SaveBase64Image(insuranceWarrantyRecordInfoCollect[i], FileHelper.GetUpLoadRelativePath(), out absulotePath);
                                long size = 0;
                                FileHelper.GetImageInfo(absulotePath + uploadFile.FilePath.Split('/').Last(), ref size, ref aLength);
                                uploadFile.FileSize = size;
                                var fileName = FileHelper.GetFileNameNoExtension(uploadFile.FilePath);
                                uploadFile.FileName = fileName;

                                responseResult.Success = result = ServiceFactory.UploadFilesServiceInstance.AddEntities(uploadFile).ID > 0;
                            }
                        }

                    }
                    if (responseResult.Success)
                    {
                        ts.Complete();
                    }
                    else
                    {
                        ts.Dispose();
                    }
                }
                catch (Exception e)
                {
                    responseResult.Message = e.ToString();
                    ts.Dispose();
                }
            }
            responseResult.Message = responseResult.Success ? "上传成功" : "上传失败";
            ViewBag.CollectWithType = model.InfoCollectWith;
            model.InsuranceWarrantyRecord =
                ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(model.InsuranceWarrantyRecordID);
            return PartialView("InfoCollectItems", model.InsuranceWarrantyRecord);
        }
        #endregion

        #region 分拣中心
        [HttpPost]
        public ActionResult SortingCenterList(SortingCenterModel model)
        {
            var total = 0;
            var list = (from a in ServiceFactory.SortingCenterServiceInstance.GetPagingList(model, out total).AsNoTracking()
                        join b in ServiceFactory.D_ProvinceServiceInstance.LoadEntities(t => true) on a.ProvinceId equals b.ProvinceID into temp1
                        from c in temp1.DefaultIfEmpty()
                        join d in ServiceFactory.D_CityServiceInstance.LoadEntities(t => true) on a.CityId equals d.CityID into temp2
                        from e in temp2.DefaultIfEmpty()
                        select new
                        {
                            a.ID,
                            a.SortingCenterName,
                            a.IsAvailable,
                            a.LastModifyBy,
                            a.LastModifyTime,
                            c.ProvinceName,
                            e.CityName,
                            a.Address,
                            a.ContactName,
                            a.ContactPhone
                        }).ToList();
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 维修服务商
        [HttpPost]
        public JsonResult ServiceProviderBranchList(AccessoriesQuotationModel model, long provinceId = 0, long cityId = 0)
        {
            var total = 0;
            var expressionWhere = PredicateExtensions.True<AccessoriesQuotation>().And(o => o.IsAvailable);
            if (model.AccessoriesLevelID > 0)
                expressionWhere = expressionWhere.And(o => o.AccessoriesLevelId == model.AccessoriesLevelID);
            if (model.AccessoriesTypeId > 0)
                expressionWhere = expressionWhere.And(o => o.AccessoriesLevel.AccessoriesTypeID == model.AccessoriesTypeId);
            if (model.ServiceType > 0)
                expressionWhere = expressionWhere.And(o => o.ServiceType == model.ServiceType);
            if (model.ProductModelId > 0)
                expressionWhere = expressionWhere.And(o => o.ProductModelId == model.ProductModelId);

            var branchExpressionWhere = PredicateExtensions.True<ServiceProviderBranch>().And(o => o.IsAvailable);
            if (provinceId > 0)
                branchExpressionWhere = branchExpressionWhere.And(o => o.ProvinceId == provinceId);
            if (cityId > 0)
                branchExpressionWhere = branchExpressionWhere.And(o => o.CityId == cityId);

            var list = (from accessoriesQuotation in ServiceFactory.AccessoriesQuotationServiceInstance.LoadEntities(expressionWhere)
                        join serviceProvider in ServiceFactory.ServiceProviderServiceInstance.LoadEntities(n => true) on accessoriesQuotation.ServiceProviderId
                    equals serviceProvider.ID
                        join serviceProviderBranch in ServiceFactory.ServiceProviderBranchServiceInstance.LoadEntities(branchExpressionWhere)
                    on serviceProvider.ID equals serviceProviderBranch.ServiceProviderId
                        select new
                        {
                            ServiceProviderBranchID = serviceProviderBranch != null ? serviceProviderBranch.ID : 0,
                            ServiceProviderBranchName = serviceProviderBranch != null ? serviceProviderBranch.BranchName : "",
                            serviceProvider.ServiceProviderName,
                            ModelName = accessoriesQuotation.ProductModels.ModelName,
                            CityName = serviceProviderBranch != null ? serviceProviderBranch.D_City.CityName : "",
                            ProvinceName = serviceProviderBranch != null ? serviceProviderBranch.D_Province.ProvinceName : "",
                            Address = serviceProviderBranch != null ? serviceProviderBranch.Address : "",
                            accessoriesQuotation.QuotationPrice
                        }).Distinct();
            total = list.Count();
            var dataList = list.OrderBy(o => o.ServiceProviderName).ThenBy(o => o.ServiceProviderBranchName)
                .Skip((model.PageIndex - 1) * model.iDisplayLength).Take(model.iDisplayLength).ToList();
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = dataList
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 保存合同记录
        public ActionResult SaveInsuranceWarrantyRecordContractInfo(InsuranceWarrantyRecordContractInfo model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Add
            };
            var iwrImages = Request.Files;
            string folderName = string.Format("/UploadFile/File/workOrder/{0}/{1}/{2}/", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            string fullPath = Server.MapPath(folderName);
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    if (iwrImages != null && iwrImages.Count > 0)
                    {
                        for (int i = 0; i < iwrImages.Count; i++)
                        {
                            var uploadFile = new InsuranceWarrantyRecordContractInfo();
                            var iwrImage = iwrImages[i];
                            if (iwrImage == null)
                            {
                                responseResult.Message = "选择的图片格式有误或者没有选择上传的图片！";
                                continue;
                            }
                            string fileName = System.Guid.NewGuid().ToString() + ".png";
                            bool result = FileHelper.GetPicThumbnail(iwrImage, 0, fullPath, fileName);
                            if (!result)
                            {
                                responseResult.Message = "图片保存错误！";
                                continue;
                            }
                            uploadFile.InsuranceWarrantyRecordID = model.InsuranceWarrantyRecordID;
                            uploadFile.PicPath = folderName + fileName;
                            uploadFile.ContractName = fileName;
                            uploadFile.FileSize = iwrImage.ContentLength;
                            uploadFile.CreatedBy = CurrentUser.UserAccount;
                            uploadFile.CreatedTime = DateTime.Now;
                            responseResult.Success = ServiceFactory.InsuranceWarrantyRecordContractInfoServiceInstance.AddEntities(uploadFile).ID > 0;
                        }
                    }
                    if (responseResult.Success)
                    {
                        ts.Complete();
                    }
                    else
                    {
                        ts.Dispose();
                    }
                }
                catch (Exception e)
                {
                    responseResult.Message = e.ToString();
                    ts.Dispose();
                }
            }

            return Json(new
            {
                success = responseResult.Success,
                message = responseResult.Message
            });
        }
        #endregion

        #region 删除合同图片
        [HttpPost]
        public JsonResult DeleteInsuranceWarrantyRecordContractInfo(int id)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Delete
            };
            var entity = ServiceFactory.InsuranceWarrantyRecordContractInfoServiceInstance.LoadById(id);
            if (entity == null)
            {
                responseResult.Message = "参数错误！";
            }
            else
            {
                responseResult.Success = ServiceFactory.InsuranceWarrantyRecordContractInfoServiceInstance.DeleteEntities(entity);
            }
            return Json(new
            {
                success = responseResult.Success,
                message = responseResult.Message
            });
        }
        #endregion
    }
}